package com.frxuexi.lib_base

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import java.io.File
import java.text.SimpleDateFormat

abstract class BaseViewModel<UiIntent:IUiIntent>:ViewModel() {
    val channel = Channel<UiIntent>()

    private var _state= MutableStateFlow<UiState>(UiState.onLoading)
    val state:StateFlow<UiState>
        get() = _state

    init {
        viewModelScope.launch {
            channel.receiveAsFlow().collect{
                handleIntent(it)
            }
        }
    }

    fun toDateTime(time:Long):String{
       return SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time)
    }

    fun toDate(time:Long):String{
        return SimpleDateFormat("yyyy-MM-dd").format(time)
    }

    fun toTime(time:Long):String{
        return SimpleDateFormat("HH:mm:ss").format(time)
    }


    /**
     * 处理意图
     */
    abstract fun handleIntent(it: UiIntent)

    /**
     * 发送意图
     */
    fun sendIntent(intent: UiIntent){
        viewModelScope.launch {
            channel.send(intent)
        }
    }

    /**
     * 网络请求
     */
    fun httpRequest(request:Flow<ApiResp<Any>>,type: RequestType=RequestType.DEFAULT){
        viewModelScope.launch {
            request.flowOn(Dispatchers.IO)
                .catch {
                    Log.i("===",it.message.toString())
                }.collect{
                    if(it.statusCode==200 || it.code==0){
                        _state.value=UiState.onSuccess(it.data?:it.datas,type)
                    }else{
                        _state.value=UiState.onError(it.msg!!)
                    }
                }
        }
    }


    /**
     * 网络请求
     */
    fun roomRequest(request:Flow<Any>,type: RequestType=RequestType.DEFAULT){
        viewModelScope.launch {
            request.flowOn(Dispatchers.IO)
                .catch {
                    Log.i("===",it.message.toString())
                }.collect{
                    if(it!=null){
                        _state.value=UiState.onSuccess(it,type)
                    }else{
                        _state.value=UiState.onError("操作失败")
                    }
                }
        }
    }

    fun download(url:String,file:File){
        viewModelScope.launch {
            DownloadUtil.download(url, file).flowOn(Dispatchers.IO)
                .catch {
                    Log.i("===",it.message.toString())
                }.collect{
                    _state.value=it
                }
        }
    }

    fun scanFile(file: File){
        viewModelScope.launch {
            try {
                val files = file.listFiles().toList()
                _state.value=UiState.onSuccess(files,RequestType.SCAN)
            }catch (e:Exception){
                _state.value=UiState.onError("没有此目录")
            }
        }
    }
}